/*判断用户是否合法输入*/
var checkFormValidity = true;

function checkFormValidityAll() {
    checkFormValidityPhoneNumber();
    checkFormValidityQuestionDetail();
    checkIsSubmit();
}

function checkFormValidityPhoneNumber() {
    // 判断手机号是否为正常数字且为11位数字
    if (isNaN(document.getElementById("phoneNumber").value) || !/^\d{11}$/.test(document.getElementById("phoneNumber").value)) {
        alert("请输入正确的手机号");
    }
}

function checkFormValidityQuestionDetail() {
    // 判断问题描述是否多于400个字
    if (document.getElementById("questionDetail").value.length > 400) {
        alert("问题描述不能多于400个字");
    }

    // 判断问题描述是否为空
    if (document.getElementById("questionDetail").value.length < 1) {
        alert("问题描述不能为空");
    }
}

function checkIsSubmit() {
    if(checkFormValidity) {
        event.preventDefault();
        sendComplaintFormData();
    } else {
        document.getElementById("myForm").action = "#";
    }
}

function sendComplaintFormData() {
    var issueType = document.getElementById("TypeOfComplaint").value;
    var issueDetails = document.getElementById("questionDetail").value;
    var phoneNumber = document.getElementById("phoneNumber").value;

    var complaintRecord = {
        issueType: issueType,
        issueDetails: issueDetails,
        phoneNumber: phoneNumber
    };

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/complaint1", true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.onreadystatechange = function () {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200) {
                alert(xhr.responseText);
                window.location.href = "complaint.html";
            } else {
                alert("Error: " + xhr.status);
            }
        }
    };
    xhr.send(JSON.stringify(complaintRecord));
}